/**
 * Created by wangyazheng on 17/4/11.
 */
import React, {Component} from "react";
import {restApiRequest} from "../Public/Api/Public";
import {ListView, PullToRefresh, Toast} from "antd-mobile";
import LazyLoad from "react-lazyload";

//每页显示数据的条数
const pageSize = 5;
let pageNum = 1;
let product_url = '/shop/api/majorlist';
let old_product_url = '/V2/product/oldProduct';
let ProductInfoList = [];
export default class HomePage extends Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            }),
            foot: 0,
            isRefreshing: false,
        };
    }

    componentWillMount() {
        // console.log(this.props.location.state, '----->this.props')
        ProductInfoList = [];
        pageNum = 1;

        let param = {page_num: pageNum, page_size: pageSize};
        let jsonData = restApiRequest.getSign(param);
        // let product_url = 'shop/api/majorlist';
        this.fetchProductListData(product_url, jsonData);
    }

    //获取商品列表
    fetchProductListData(url, jsonData) {
        restApiRequest.fetchp(url, jsonData).then((response) => {
            if (!response.ok) {
                var error = new Error(response.statusText);
                error.response = response;
                throw error;
            } else {
                return response.json();
            }
        }).then((response_json) => {
            // console.log('productList--->', response_json);
            if (response_json.code === '0000') {
                let responseData = response_json.data;
                //请求结果有数据
                if (responseData.major_product_list.length > 0) {
                    //请求数据小于5数据加载完
                    if (responseData.major_product_list.length < pageSize) {
                        //加载完毕
                        this.setState({foot: 1});
                    } else {
                        //隐藏
                        this.setState({foot: 0});
                    }
                    if (responseData.major_product_list != null) {
                        //每次请求结果push到商品列表数组进行渲染
                        for (var i = 0; i < responseData.major_product_list.length; i++) {
                            ProductInfoList.push(responseData.major_product_list[i]);
                        }
                        this.setState({
                            dataSource: this.state.dataSource.cloneWithRows(ProductInfoList),
                        });
                    }
                } else {
                    this.setState({foot: 1});
                }
                this.setState({isRefreshing: false})
            } else {
                return Toast.offline(response_json.msg, 2)
            }
        }).catch((ex) => {
            console.log(ex);
        });
    }

    //点击跳转详情
    jumpRow(rowData) {
        this.props.history.push({
            pathname: '/ProductDetail',
        })
        localStorage.setItem('ProductDetail', JSON.stringify(rowData))
    }

    //下拉刷新
    onRefresh() {
        this.setState({isRefreshing: true});
        ProductInfoList = [];
        let param = {page_num: 1, page_size: pageSize};
        let jsonData = restApiRequest.getSign(param);
        // let product_url = 'shop/api/majorlist';
        this.fetchProductListData(product_url, jsonData);
    }

    //加载更多
    onEndReached() {
        if (this.state.foot != 0) {
            return;
        }
        this.setState({
            foot: 2,
        });
        pageNum++;
        console.log('当前页数:' + pageNum);
        let param = {page_num: pageNum, page_size: pageSize};
        let jsonData = restApiRequest.getSign(param);
        this.fetchProductListData(product_url, jsonData);
    }

    renderHeader() {
        return (
            <div style={{height: '.3rem'}}/>
        )
    }

    renderFooter() {
        if (this.state.foot === 0) {            //上滑加载更多
            return (
                <div className="hom-list-footer">
                    <svg className="hom-list-footer-icon">
                        <use xlinkHref='#icon-ico_page_bottom_dog'></use>
                    </svg>
                    <p
                        className="hom-list-footer-text">往上滑加载更多...</p>
                </div>);
        } else if (this.state.foot === 1) {    //加载完毕
            return (
                <section className="hom-list-footer" style={{
                    marginBottom: 0,
                    paddingBottom: 0
                }}>
                    <svg className="hom-list-footer-icon">
                        <use xlinkHref={'#icon-ico_page_bottom_dog'}></use>
                    </svg>
                    <p className="hom-list-footer-text">我是有底线的</p>
                </section>);
        } else if (this.state.foot === 2) {     //加载中
            return (
                <div className="hom-list-footer">
                    <svg className="hom-list-footer-icon">
                        <use xlinkHref='#icon-ico_page_bottom_dog'></use>
                    </svg>
                    <p className="hom-list-footer-text">拼命加载中...</p>
                </div>);
        }
    }


    render() {
        const renderList = (rowData, sectionID, rowID) => {

            let big = '0';
            let small = '0';
            if (rowData.price != undefined) {
                let price_array = rowData.price.split('.');
                big = price_array[0];
                small = price_array[1].substr(0, 1);
            } else {
            }

            if (rowData.is_topic === 1) {
                return (
                    <div
                        key={rowID}
                        onClick={() => this.jumpRow(rowData)}
                        className="home-list"
                    >
                        <img className="home-list-img" src={rowData.top_image_url}/>
                    </div>
                )
            } else {
                return (
                    <div
                        key={rowID}
                        onClick={() => this.jumpRow(rowData)}
                        className="home-list"
                    >
                        <section className="home-list-imgbox">

                            <LazyLoad
                                offset={100}
                                debounce={500}
                                placeholder={
                                    <section className="home-list-lazyload">
                                        <svg className="home-list-placeholder">
                                            <use xlinkHref={'#icon-ico_page_bottom_dog'}></use>
                                        </svg>
                                    </section>
                                }
                            >
                                <img className="home-list-img" src={rowData.top_image_url}/>
                            </LazyLoad>

                            <section className="home-list-imgtips">
                                <svg>
                                    <use xlinkHref='#icon-ico_corner_tag'></use>
                                </svg>
                                <section className="home-list-tips">
                                    <p className="home-list-tipstext">{rowData.use_scope}</p>
                                    <section className="home-list-price">
                                        <span>￥</span>
                                        <span>{big}</span>
                                        <span>.{small}</span>
                                    </section>
                                </section>
                            </section>

                            <section className="home-arrows-box">
                                <div className="home-arrows-left"/>
                                <div className="home-arrows-right"/>
                            </section>
                        </section>

                        <section className="home-text-box">
                            <p>{rowData.major_product_shortname}</p>
                            <p>{rowData.major_product_name}</p>
                        </section>

                    </div>
                )
            }
        };

        return (
            <div>
                <ListView ref='productList'
                          dataSource={this.state.dataSource}
                          initialListSize={4}
                          renderRow={renderList}
                          scrollRenderAheadDistance={1000}
                          scrollEventThrottle={20}
                          renderHeader={this.renderHeader.bind(this)}
                          renderFooter={this.renderFooter.bind(this)}
                          onEndReached={this.onEndReached.bind(this)}
                          onEndReachedThreshold={10}
                          style={{
                              height: window.innerHeight,
                              overflow: 'auto',
                          }}
                          pullToRefresh={
                              <PullToRefresh
                                  refreshing={this.state.isRefreshing}
                                  onRefresh={this.onRefresh.bind(this)}
                                  indicator={{deactivate: '下拉'}}
                              />
                          }
                />
            </div>

        )
    }
}
